package conexion;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import objetos.FiltroBusquedaJugador;
import util.Constantes;

public class Buscar {

	private static String setCookie = Conexion.EASW_KEY + "; " + Conexion.easf_sess_com + "; FUTWebPhishing" + Conexion.FUTWebPhishing;

	public static void busquedaContrato(){
		URL urlsearchUser;
		HttpsURLConnection connectionSearchUser = null;
		String lineSearchUser="0";

		try{	
			int limite=100000;
			int monedasRestantes=Conexion.monedas();
			System.out.println("Monedas restantes: "+monedasRestantes);
			while(monedasRestantes>limite){
				System.out.println("Buscando...");
				urlsearchUser = new URL("https://utas.fut.ea.com/ut/game/fifa13/auctionhouse?maxb=300&num=100&blank=10&cat=contract&type=development&start=0&lev=gold");
				connectionSearchUser = (HttpsURLConnection)urlsearchUser.openConnection();
				connectionSearchUser.setRequestMethod("POST");
				connectionSearchUser.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31");
				connectionSearchUser.setRequestProperty("Cookie", setCookie);
				connectionSearchUser.setRequestProperty("Content-Type", "application/json");	
				connectionSearchUser.setRequestProperty("X-UT-SID", Conexion.XUTSID);	
				connectionSearchUser.setRequestProperty("X-HTTP-Method-Override", "GET");
				connectionSearchUser.setUseCaches (false);connectionSearchUser.setDoInput(true);connectionSearchUser.setDoOutput(true);		
						      
				//Get Response	
				InputStream isSearchUser = connectionSearchUser.getInputStream();		
				BufferedReader rdSearchUser = new BufferedReader(new InputStreamReader(isSearchUser));		
				lineSearchUser = rdSearchUser.readLine();
				String lineSearchUser2 = lineSearchUser;
				System.out.println(lineSearchUser);
				
				String tradeId;	String resourceId;	
				int discardValue=0;	int currentBid=0; int startingBid=0; int expires=0; int contador=0;
	            
	    	    while (lineSearchUser.indexOf("itemData") > -1) {
	    	    	lineSearchUser = lineSearchUser.substring(lineSearchUser.indexOf("itemData")+"itemData".length(),lineSearchUser.length());
	    		    contador++; 
	    		}

				if(monedasRestantes>300){
					for(int i=0;i<contador;i++){
						resourceId = JsonParse.resourceId(lineSearchUser2, i);
						System.out.println("Contrato: "+(i+1)+" de "+contador);
						if(resourceId.equalsIgnoreCase("1347178286")==true || resourceId.equalsIgnoreCase("1347178283")==true){
							int buyNowPrice = JsonParse.buyNowPrice(lineSearchUser2, i);
							System.out.println("La puja comienza en: "+startingBid);
							if(buyNowPrice==300){
								tradeId = JsonParse.tradeId(lineSearchUser2, i);
								System.out.println("TradeId: "+tradeId);
								int puja=300;
								Comprar.estadoPuja(tradeId,puja);
							}else if(buyNowPrice==250){
								tradeId = JsonParse.tradeId(lineSearchUser2, i);
								System.out.println("TradeId: "+tradeId);
								int puja=250;
								Comprar.estadoPuja(tradeId,puja);
							}else if(buyNowPrice==200){
								tradeId = JsonParse.tradeId(lineSearchUser2, i);
								System.out.println("TradeId: "+tradeId);
								int puja=200;
								Comprar.estadoPuja(tradeId,puja);
							}
						}
					}
				}else{/*listaCompra();*/}
				Thread.sleep(700);
			}
			SinAsignar.listaSinAsignar();
		}catch(Exception e){} 
	}
	
	
public void buscarPujarCarta(String tipoCarta, String categoriaCarta, String tipoHabilidad, String valorHabilidad, String minPrecio, String maxPrecio, String nivel){
		
	URL urlSearchUser;
	HttpsURLConnection connectionSearchUser = null;
	String lineSearchUser="0";

	try{	
		int limite=100000;
		int monedasRestantes=Conexion.monedas();
		System.out.println("Monedas restantes: "+monedasRestantes);
		while(monedasRestantes>limite){
				System.out.println("Buscando "+tipoCarta);
				FiltroBusquedaJugador filtro = new FiltroBusquedaJugador();
				//TODO cargar el objeto filtro con los valores de la interfaz de ususario
				urlSearchUser = montarUrl(filtro);
				connectionSearchUser = (HttpsURLConnection)urlSearchUser.openConnection();
				connectionSearchUser.setRequestMethod("POST");
				connectionSearchUser.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31"); //Hacemos creer a EA que somos un navegador
				connectionSearchUser.setRequestProperty("Cookie", setCookie); //Enviamos las 3 cookies
				connectionSearchUser.setRequestProperty("Content-Type", "application/json");	
				connectionSearchUser.setRequestProperty("X-UT-SID", Conexion.XUTSID);	
				connectionSearchUser.setRequestProperty("X-HTTP-Method-Override", "GET");
				connectionSearchUser.setUseCaches (false);connectionSearchUser.setDoInput(true);connectionSearchUser.setDoOutput(true);		
						      
				connectionSearchUser = (HttpsURLConnection)urlSearchUser.openConnection();
				connectionSearchUser.setRequestMethod("POST");
				connectionSearchUser.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31");
				connectionSearchUser.setRequestProperty("Cookie", setCookie);
				connectionSearchUser.setRequestProperty("Content-Type", "application/json");	
				connectionSearchUser.setRequestProperty("X-UT-SID", Conexion.XUTSID);	
				connectionSearchUser.setRequestProperty("X-HTTP-Method-Override", "GET");
				connectionSearchUser.setUseCaches (false);connectionSearchUser.setDoInput(true);connectionSearchUser.setDoOutput(true);		
						      
				//Get Response	
				InputStream isSearchUser = connectionSearchUser.getInputStream();		
				BufferedReader rdSearchUser = new BufferedReader(new InputStreamReader(isSearchUser));		
				lineSearchUser = rdSearchUser.readLine();
				String lineSearchUser2 = lineSearchUser;
				System.out.println(lineSearchUser);
				
				String tradeId;	String resourceId;	
				int discardValue=0;	int currentBid=0; int startingBid=0; int expires=0; int contador=0;
	            
	    	    while (lineSearchUser.indexOf("itemData") > -1) {
	    	    	lineSearchUser = lineSearchUser.substring(lineSearchUser.indexOf("itemData")+"itemData".length(),lineSearchUser.length());
	    		    contador++; 
	    		}

				if(monedasRestantes>300){
					for(int i=0;i<contador;i++){
						resourceId = JsonParse.resourceId(lineSearchUser2, i);
						System.out.println("Contrato: "+(i+1)+" de "+contador);
						if(resourceId.equalsIgnoreCase("1347178286")==true || resourceId.equalsIgnoreCase("1347178283")==true){
							int buyNowPrice = JsonParse.buyNowPrice(lineSearchUser2, i);
							System.out.println("La puja comienza en: "+startingBid);
							if(buyNowPrice==300){
								tradeId = JsonParse.tradeId(lineSearchUser2, i);
								System.out.println("TradeId: "+tradeId);
								int puja=300;
								Comprar.estadoPuja(tradeId,puja);
							}else if(buyNowPrice==250){
								tradeId = JsonParse.tradeId(lineSearchUser2, i);
								System.out.println("TradeId: "+tradeId);
								int puja=250;
								Comprar.estadoPuja(tradeId,puja);
							}else if(buyNowPrice==200){
								tradeId = JsonParse.tradeId(lineSearchUser2, i);
								System.out.println("TradeId: "+tradeId);
								int puja=200;
								Comprar.estadoPuja(tradeId,puja);
							}
						}
					}
				}else{/*listaCompra();*/}
				Thread.sleep(700);
			}
			SinAsignar.listaSinAsignar();
		}catch(Exception e){} 
	}
	
	public URL montarUrl(FiltroBusquedaJugador filtro) throws MalformedURLException{
		//tipoCarta: player/training/staff
		//Entrenador --> type=staff&start=0&blank=10&cat=manager&num=16&lev=gold&macr=300
//		jugador --> type=player&lev=gold&team=73&num=16&form=f41212&start=0&leag=16&micr=1500000&nat=46&zone=attacker
		
		StringBuffer strUrl = new StringBuffer();
		strUrl.append(Constantes.URL_PUJAS+Constantes.PARAM_TIPO_CARTA+"="+filtro.getTipoCarta()+"&"+Constantes.PARAM_START+"=0&"+Constantes.PARAM_NUM_RESULTADOS+"=16");
		
		if(filtro.getCategoriaCarta() != ""){
			strUrl.append("&");
			strUrl.append(Constantes.PARAM_CATEGORIA_CARTA);
			strUrl.append("=");
			strUrl.append(filtro.getCategoriaCarta());
		}
		if(filtro.getNivel() != ""){
			strUrl.append("&");
			strUrl.append(Constantes.PARAM_NIVEL);
			strUrl.append("=");
			strUrl.append(filtro.getNivel());
		}
		if(filtro.getMaxPrecio() != ""){
			strUrl.append("&");
			strUrl.append(Constantes.PARAM_MAX_PRECIO);
			strUrl.append("=");
			strUrl.append(filtro.getMaxPrecio());
		}
		if(filtro.getMinPrecio() != ""){
			strUrl.append("&");
			strUrl.append(Constantes.PARAM_MIN_PRECIO);
			strUrl.append("=");
			strUrl.append(filtro.getMinPrecio());
		}
		if(filtro.getPosicion() != ""){
			strUrl.append("&");
			strUrl.append(Constantes.JUGADOR_POSICION);
			strUrl.append("=");
			strUrl.append(filtro.getPosicion());
		}
		if(filtro.getEquipo() != ""){
			strUrl.append("&");
			strUrl.append(Constantes.JUGADOR_EQUIPO);
			strUrl.append("=");
			strUrl.append(filtro.getEquipo());
		}
		if(filtro.getFormacion() != ""){
			strUrl.append("&");
			strUrl.append(Constantes.JUGADOR_FORMACION);
			strUrl.append("=");
			strUrl.append(filtro.getFormacion());
		}
		if(filtro.getLiga() != ""){
			strUrl.append("&");
			strUrl.append(Constantes.JUGADOR_LIGA);
			strUrl.append("=");
			strUrl.append(filtro.getLiga());
		}
		if(filtro.getNacionalidad() != ""){
			strUrl.append("&");
			strUrl.append(Constantes.JUGADOR_NACIONALIDAD);
			strUrl.append("=");
			strUrl.append(filtro.getNacionalidad());
		}
		
		
		URL url = new URL(Constantes.URL_PUJAS+Constantes.PARAM_TIPO_CARTA+"="+filtro.getTipoCarta()+"&"+Constantes.PARAM_START+"=0&"+Constantes.PARAM_NUM_RESULTADOS+"=16&"+Constantes.PARAM_NIVEL+"="+filtro.getNivel());
		return url;
	}

}
